<template>
  <div style="padding: 20px;">
    <div class="topLocation">今日资讯管理 / 今日资讯</div>
    <div class="topTool">
      <div class="group">发布者姓名：</div>
      <el-input v-model="searchPublisherName" placeholder="请输入发布者姓名" style="margin-right: 50px;"></el-input>
      <div class="group">资讯名称：</div>
      <el-input v-model="searchNewsName" placeholder="请输入资讯名称" style="margin-right: 50px;"></el-input>
      <div class="group">资讯来源：</div>
      <el-input v-model="searchNewsSource" placeholder="请输入资讯来源" style="margin-right: 50px;"></el-input>
      <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      <el-button type="primary" :icon="Plus" @click="handleAdd">添加</el-button>
      <el-button type="danger" :icon="Delete" @click="handleDelList" v-if="multipleSelection.length > 0">删除选中资讯
      </el-button>
    </div>
    <el-table
        :data="newsData"
        :header-cell-style="{ background: '#f6f9fa'}"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column prop="id" label="ID" sortable></el-table-column>
      <el-table-column prop="publisherName" label="发布者姓名"></el-table-column>
      <el-table-column prop="newsName" label="资讯名称"></el-table-column>
      <el-table-column prop="newsSource" label="资讯来源"></el-table-column>
      <el-table-column prop="publishTime" label="发布时间" :formatter="formatDate"></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button type="primary" :icon="Document" size="small" @click="showDetails(row)">详细</el-button>
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 资讯信息弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
      <el-form :model="form" label-width="100px">
        <el-form-item label="资讯名称">
          <el-input v-model="form.newsName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="资讯内容">
          <el-input type="textarea" v-model="form.newsContent" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="资讯来源">
          <el-input v-model="form.newsSource" autocomplete="off"/>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogOk">确定</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详细信息弹窗 -->
    <el-dialog
        title="资讯详细内容"
        v-model="detailsDialogVisible"
        :close-on-click-modal="false"
        width="50%">
      <div class="detail-content">
        <div v-html="formattedDetails"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import {ref, onMounted, computed} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Edit, Plus, Search, Document} from '@element-plus/icons-vue';
import {useRoute} from "vue-router";

// 响应式变量
const newsData = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const searchPublisherName = ref('');
const searchNewsName = ref('');
const searchNewsSource = ref('');

// 通过 useRoute 获取路由参数
const route = useRoute();
const name = ref(route.query.name ? String(route.query.name) : '');
const role = ref(route.query.role ? String(route.query.role) : '');

// 日期格式化函数
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '无日期';
  const date = new Date(cellValue);
  if (isNaN(date.getTime())) {
    return '无效日期';
  }
  return date.toLocaleDateString();
};

// 组件挂载时加载数据
onMounted(() => {
  getData();
});

// 获取数据
const getData = () => {
  axios.get('http://localhost:8080/news/page', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      publisherName: searchPublisherName.value,
      newsName: searchNewsName.value,
      newsSource: searchNewsSource.value,
    }
  }).then(response => {
    newsData.value = response.data.records;
    total.value = response.data.total;
  }).catch(error => {
    console.error(error);
  });
};

// 当前页码变化
const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getData();
};

// 每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  getData();
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
      '您确定要删除资讯【' + row.newsName + '】吗?',
      '危险操作',
  ).then(() => {
    axios.delete(`http://localhost:8080/news/delete/${row.id}`)
        .then(response => {
          ElMessage({
            type: 'success',
            message: response.data,
          });
          getData();
        })
        .catch(error => {
          ElMessage({
            type: 'error',
            message: '删除失败',
          });
          console.error(error);
        });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!',
    });
  });
};

// 删除请求
const delNews = (id) => {
  axios.delete(`http://localhost:8080/news/${id}`)
      .then(response => {
        getData();
      })
      .catch(error => {
        console.error(error);
      });
};

// 查询
const handleSearch = () => {
  const params = {
    publisherName: searchPublisherName.value || null,
    newsName: searchNewsName.value || null,
    newsSource: searchNewsSource.value || null
  };
  axios.get('http://localhost:8080/news/search', {params})
      .then(response => {
        newsData.value = response.data;
        total.value = response.data.length; // 假设返回的是数组，直接使用数组的长度作为总数
      })
      .catch(error => {
        console.error(error);
        ElMessage.error('查询失败');
      });
};

// 字段排序
const handleSortChange = (sortData) => {
  const {prop, order} = sortData;
  newsData.value = newsData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });
};

// 创建响应式变量multipleSelection，用于存储当前选中的数据行
let multipleSelection = ref([]);
// 处理表格行选中状态变化的方法，val是当前选中的数据行数组
const handleSelectionChange = (val) => {
  // 清空数组，确保每次更新都是最新选中状态
  multipleSelection.value = [];
  val.forEach(item => {
    multipleSelection.value.push(item.id); // 将选中的每一行数据的id存入multipleSelection数组中
  });
};

// 批量删除
const handleDelList = () => {
  ElMessageBox.confirm(
      '您确定要删除选择的资讯吗?',
      '危险操作',
  ).then(() => {
    const newsIds = multipleSelection.value;
    axios.delete('http://localhost:8080/news/delete/batch', { data: newsIds })
        .then(response => {
          getData();
          ElMessage({ type: 'success', message: '完成批量删除！' });
        })
        .catch(error => {
          console.error(error);
          ElMessage({ type: 'error', message: '删除失败！' });
        });
  }).catch(() => {
    ElMessage({ type: 'info', message: '取消删除!' });
  });
};

// 弹窗相关变量
const dialogFormVisible = ref(false); // 控制弹窗显示
const form = ref({
  id: '',
  publisherName: '',
  newsName: '',
  newsContent: '',
  newsSource: '',
  publishTime: '',
}); // 表单数据
const dialogType = ref('add'); // 初始化弹出框的类型为增加弹窗

// 详细信息弹窗相关变量
const detailsDialogVisible = ref(false); // 控制详细信息弹窗显示
const selectedDetails = ref(''); // 选中行的详细信息

// 显示详细信息
const showDetails = (row) => {
  selectedDetails.value = row.newsContent;
  detailsDialogVisible.value = true;
};

// 格式化详细内容
const formattedDetails = computed(() => {
  // 利用正则表达式找出网址并转为链接
  const regex = /((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi;
  return selectedDetails.value.replace(regex, '<a href="$1" target="_blank">$1</a>');
});

// 处理添加按钮点击事件
const handleAdd = () => {
  dialogFormVisible.value = true;
  dialogType.value = 'add';
// 设置表单
  form.value = {
    id: '',
    publisherName: name.value,
    newsName: '',
    newsContent: '',
    newsSource: '',
    publishTime: '',
  };
};

// 设置弹窗的标题
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增资讯' : '编辑资讯';
});

// 确定按钮点击事件
const dialogOk = () => {
  if (!form.value.publishTime) {
    form.value.publishTime = new Date().toISOString().slice(0, 10); // 设置默认日期为今天
  }
  dialogFormVisible.value = false;
  if (dialogType.value === 'add') {
    addNews();
  } else {
    updateNews();
  }
};

// 添加资讯
const addNews = () => {
  const newNews = {...form.value};
  axios.post('http://localhost:8080/news/add', newNews)
      .then(response => {
        ElMessage.success('添加资讯成功');
        getData(); // 在添加数据后调用获取数据的方法
      })
      .catch(error => {
        ElMessage.error('添加资讯失败');
        console.error(error);
      });
};

// 处理编辑按钮点击事件
const handleEdit = (row) => {
  form.value = {...row};
  dialogType.value = 'edit';
  dialogFormVisible.value = true;
};

// 更新资讯
const updateNews = () => {
  const id = form.value.id;
  const updatedNews = {...form.value};
  axios.put(`http://localhost:8080/news/update/${id}`, updatedNews)
      .then(response => {
        ElMessage.success('更新资讯成功');
        getData(); // 更新表格显示
      })
      .catch(error => {
        ElMessage.error('更新资讯失败');
        console.error(error);
      });
};

</script>

<style scoped>
.topLocation {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 文字颜色为黑色 */
  padding: 10px;
  border-bottom: 2px solid #000; /* 底部边框，黑色 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
  margin-bottom: 20px; /* 增加距离 */
}

.topTool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.group {
  white-space: nowrap; /* 防止文字换行 */
  font-size: 14px; /* 设置字体大小为 14px */
}
</style>
